package com.ly.common.core.config;

import lombok.Data;
import lombok.extern.slf4j.Slf4j;
import org.springframework.context.annotation.Bean;
import org.springframework.stereotype.Component;

import java.util.concurrent.*;

/**
 * 线程配置
 * @author luoyun
 * @date 2023年7月7日
 */
@Data
@Component
@Slf4j
public class ThreadConfig {

    //@Value(value = "${threadpool.core-poolsize}")
    private Integer corePoolSize = 1;

    //@Value(value = "${threadpool.maximum-poolsize}")
    private Integer maximumPoolSize = 3;

    //@Value(value = "${threadpool.keep-alivetime}")
    private Long keepAliveTime = 60L;

    /**
     * @return ThreadPoolExecutor
     * @Title: mssqlDataSyncThreadPool
     * @Description:
     */
    @Bean(name = "asyncServiceExecutor")
    public ThreadPoolExecutor defaultThreadPool() {
        ThreadFactory threadFactory = Executors.defaultThreadFactory();
        ThreadPoolExecutor threadPool = new ThreadPoolExecutor(
                corePoolSize,
                maximumPoolSize,
                keepAliveTime,
                TimeUnit.SECONDS,
                new LinkedBlockingDeque<>(maximumPoolSize * 5),
                threadFactory,
                new ThreadPoolExecutor.CallerRunsPolicy()
        );
        return threadPool;
    }

    /**
     * @author Q.JI
     * @ClassName: MyExceptionHandler
     * @Description: 自定义，线程池中的线程挂掉后捕获异常
     * @date 2023年1月4日 下午3:23:29
     * @since JDK 1.8
     */
    public static class MyExceptionHandler implements Thread.UncaughtExceptionHandler {
        @Override
        public void uncaughtException(Thread t, Throwable e) {
            log.info(String.format("kafka thread name %s, msg %s", t.getName(), e.getStackTrace()));
        }
    }
}
